#include "EZ_Thread.h"

list_t 	sys_timer_list;


void sys_timer_init(void)
{	
	list_init(&sys_timer_list);
}

void timer_init(ez_timer_t *timer,
								uint32_t timeout_tick,
								void (*timeout_fun)(void *param),
								void *param,
								uint32_t flag)
{
	timer->init_tick = timeout_tick;
	timer->timeout_fun = timeout_fun;
	timer->param = param;
	timer->flag  = flag;
	list_init(&timer->tlist);
}	

void timer_start(ez_timer_t *timer)
{
	timer->start_tick =	tick_get();
	list_insert_before(&sys_timer_list,&timer->tlist);
	
}

void timer_stop(ez_timer_t *timer)
{
	list_remove(&timer->tlist);
}

void timer_contorl(ez_timer_t *timer,uint32_t flag,void *param)
{
	switch(flag)
	{
		case EZ_TIME_CTRL_SET_TIME:
				timer->init_tick = (uint32_t)param;
				break;
		case EZ_TIME_CTRL_SET_FLAG:
				timer->flag = (uint32_t)param;
				break;
		default:
				break;
	}

}
void timer_check(void)
{
	uint32_t now_tick;
	ez_timer_t *timer;
	list_t 		 *list;
	
	if(list_isempty(&sys_timer_list))
		return ;
	
	now_tick = tick_get();
	list = &sys_timer_list;
	while(&sys_timer_list != list->next)
	{
		timer = get_list_entry(list->next,ez_timer_t,tlist);
		if(now_tick - timer->start_tick > timer->init_tick)
		{
				timer->timeout_fun(timer->param);
				if(timer->flag == EZ_TIMER_CYCLE)
				{
					timer->start_tick = now_tick;
				}
				else
				{
					list_remove(&timer->tlist);
				}
		}
		list = list->next;
	}
	
}

